#ifndef __SOCK_HPP__
#define __SOCK_HPP__

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class Sock
{
private:
    static const int g_backlog = 20;

public:
    Sock(const uint16_t &port = 8080, const std::string &ip = "0.0.0.0")
        : _sock(-1), _port(port), _ip(ip)
    {
    }

    int Socket()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        return _sock;
    }

    bool Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if (bind(_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
            return false;
        return true;
    }

    bool Listen(int backlog = g_backlog)
    {
        if (listen(_sock, backlog) < 0)
            return false;
        return true;
    }

    int Accept(uint16_t *port, std::string *ip, int *accept_errno)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        int sock = accept(_sock, (struct sockaddr *)&peer, &len);
        if (sock < 0)
        {
            *accept_errno=errno;
            return -1;
        }
        *port = ntohs(peer.sin_port);
        *ip = inet_ntoa(peer.sin_addr);
        return sock;
    }

    static bool SetNonBlock(int sock)
    {
        int fl = fcntl(sock, F_GETFL);
        if (fl < 0)
            return false;
        fcntl(sock, F_SETFL, fl | O_NONBLOCK);
        return true;
    }

private:
    int _sock;
    uint16_t _port;
    std::string _ip;
};

#endif